<?php
    //课程查寻  信息处理
    function ke($jing){
        if(!$jing){
            $jing = 1;
        }else{
            foreach ($jing as $k=>$v){
                $guan = zong_shu("collect_goods","goods_id = {$v['id']}");//想学习人数
                if($v['status'] == 1){ //视频课程
                    $kai   = zong_shu("goods","goods_zhu_id = {$v['id']}"); //开课数
                }
                if($v['status'] == 2){ //语音课程
                    $kai   = zong_shu("voices","voice_zhu_id = {$v['id']}");
                }
                $jing[$k]['guan'] = $guan;
                $jing[$k]['kai']  = $kai;
                $jing[$k]['img'] = IMGS.$v['img'];
            }
        }
        return $jing;
    }
    //消费用户获得积分 以及转介用户获得收益
    function xiao_yi($covers_shu,$moneys,$users,$zhuan_user,$goods_id,$u_type,$z_type){
        if($moneys){
            //用户消费获得积分
            if($covers_shu['nums_two']){
                $xiao_huo = floor($moneys)*$covers_shu['nums_two'];
                $xiao_c   = $users['covers']+$xiao_huo;
                $x_u_h    = up_one("users","id = {$users['id']}",array("covers"=>$xiao_c));
                $xiao_cs  = "+".$xiao_huo;
                $u_x_c    = ins("users_covers",array("user_id"=>$users['id'],"shi_id"=>$goods_id,"covers"=>$xiao_cs,"type"=>$u_type,"create_at"=>time()));
            }
            //转介用户获得的积分数
            if($covers_shu['nums_eight']){
                $zhuan_huo   = floor(floor($moneys)*$covers_shu['nums_eight']);
                if($zhuan_user != 1){
                    //该转介用户状态变为已消费
                    if($zhuan_user['status'] == 1){
                        $u_z_x = up_one("zhuan","id = {$zhuan_user['id']}",array("status"=>2,"up_at"=>time()));
                    }
                    $zhu_u = sel("users","covers","id = {$zhuan_user['user_id']}");
                    $z_c   = $zhu_u['covers']+$zhuan_huo;
                    $u_z   = up_one("users","id = {$zhuan_user['user_id']}",array("covers"=>$z_c));
                    $z_cs  = "+".$zhuan_huo ;
                    $u_c_z = ins("users_covers",array("user_id"=>$zhuan_user['user_id'],"shi_id"=>$users['id'],"covers"=>$z_cs,"type"=>$z_type,"create_at"=>time()));
                }
            }
        }
    }
    //存储用户form_id
    function form_id($form_id,$user_id){
        $sel          = sel("form_id","id,form_id","user_id = {$user_id}");
        if($sel){
            $a            = explode(",",$sel['form_id']);
            array_push($a,$form_id);
            $b            = implode(",",$a);
            $up            = up_one("form_id","id = {$sel['id']}",array("form_id"=>$b));
        }else{
            $up            = ins("form_id",array("form_id"=>$form_id,"user_id"=>$user_id,"create_at"=>time()));
        }
        if($up){ return  1; }else{ return 2; }
    }
    //存储用户信息
    function user_add($code,$filed){
        $openid              = codes($code);
        $img    = I('img');
        if($img){
            $data['headimgurl'] = $img;
        }
        $name    = I('name');
        if($name){
            $data['nickname']  = $name;
            $data['city']       = I('city');
            $data['province']   = I('pro');
            $data['country']    = I('cou');
        }
        $user                = sel("users","id","openid = '{$openid}'");
        if($user){
            $data['up_at']  = time();
            $up              = up_one("users",array("id"=>$user['id']),$data);
        }else{
            $data['create_at']   = time();
            $data['openid']      = $openid;
            $ins                  = ins("users",$data);
           /* $sence                = I('sence');
            if($sence >0){
                $users             = sel("users","id","openid = '{$openid}'");
                //转介添加
                $zhuan             = sel("zhuan","id","zhuan_id = {$users['id']}");//用户只可以被一个人转介过来
                if(!$zhuan  && ($sence != $users['id'])){
                    $r = ins("zhuan",array("user_id"=>$sence,"zhuan_id"=>$users['id'],"create_at"=>time()));
                }
            }*/
        }
        $user_id= sel("users",$filed,"openid like '{$openid}'");
        return $user_id;
    }
    //冒泡排序
    function mao_pai($b,$type){
        $len=count($b);
        if($type == 1){//第一种：由大到小
            for($k=0;$k<=$len;$k++)
            {
                for($j=$len-1;$j>$k;$j--){
                    if($b[$j]>=$b[$j-1]){
                        $temp = $b[$j];
                        $b[$j] = $b[$j-1];
                        $b[$j-1] = $temp;
                    }
                }
            }
        }else{//第一种：由大到小
            for($k=0;$k<=$len;$k++)
            {
                for($j=$len-1;$j>$k;$j--){
                    if($b[$j]<$b[$j-1]){
                        $temp = $b[$j];
                        $b[$j] = $b[$j-1];
                        $b[$j-1] = $temp;
                    }
                }
            }
        }
   /*  //第二种：由小到大
      for($k=1;$k<$len;$k++)
        {
            for($j=0;$j<$len-$k;$j++){
                if($b[$j]>$b[$j+1]){
                    $temp =$b[$j+1];
                    $b[$j+1] =$b[$j] ;
                    $b[$j] = $temp;
                }
            }
        }*/
        return $b;
    }
    //汉字字符串截取
    function zhong_wen($string,$num,$jie){
        if(mb_strlen($string,'utf-8') > $num){
            $string = mb_substr($string,0,$jie,'utf-8')."...";//从0开始截取的个数
        }
        return $string;
    }
    //编辑器中得图片地址拼接
    function img_jie($pin,$content){
        //str_replace('/Public/kindeditor/','https://www.ciqinfuwu.com/Public/kindeditor/',$v['intro']);
        $img = str_replace($pin,'https://www.bozhiyingxiao.com'.$pin,$content);
        $img = str_replace("amp;",'',$img);
        return $img;
    }

    function xing($xing){
        if($xing == 1){$a = array(1);}
        if($xing == 2){$a = array(1,2);}
        if($xing == 3){$a = array(1,2,3);}
        if($xing == 4){$a = array(1,2,3,4);}
        if($xing == 5){$a = array(1,2,3,4,5);}
        return $a;
    }
    function xings($xing){
        if($xing == 4){$a = array(1);}
        if($xing == 3){$a = array(1,2);}
        if($xing == 2){$a = array(1,2,3);}
        if($xing == 1){$a = array(1,2,3,4);}
        return $a;
    }

    //获取access_token
    function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("access_token.json"));
        if ($data->expire_time < time()) {
            $appid = APP;
            $secret = SECRET;
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            $res = json_decode(httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen("access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }
    //查询多条语句
    function sels($table,$filed,$where = null,$order = null,$limit = null){
        $result = M($table)->field($filed)->where($where)->order($order)->limit($limit)->select();
        if($result){ return $result;}else{return false;}
    }
    //查询一条
    function sel($table,$filed,$where=null,$order=null,$limit=null){
        $result = M($table)->field($filed)->where($where)->order($order)->limit($limit)->find();
        if($result){ return $result;}else{return false;}
    }
    //删除一条
    function del($table,$id){
        $result = M($table)->where($id)->delete();
        if($result){ return $result;}else{return false;}
    }
    //删除多条
    function dels($table,$id){
        if(is_array($id)){
            $result = M($table)->where($id)->delete();
        }else{
            $result = M($table)->where(array("id"=>array("in",$id)))->delete();
        }
        if($result){ return $result;}else{return false;}
    }
    //添加
    function ins($table,$data){
        $result = M($table)->add($data);
        if($result){ return $result;}else{return false;}
    }
    //模糊查询查询多条语句
    function likes($table,$where = null,$order = null,$limit = null){
        $result = M($table)->where($where)->order($order)->limit($limit)->select();
        if($result){ return $result;}else{return false;}
    }
    //多表联合查询  查一条
    function join_one($table,$filed,$join,$where = null,$order){
        $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->find();//获取数据
        return $list;
    }
    //多表联合查询  查多条
    function joins($table,$filed,$join,$where = null,$order = null,$limit = null){
        $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->limit($limit)->select();//获取数据
        return $list;
    }
    //修改一条信息
    function up_one($table,$where,$data){
        $result = M($table)->where($where)->save($data);
        if($result){ return $result;}else{return false;}
    }
    //分页
    function currpage($table,$filed,$where = null,$pagesize,$currpage,$order){
        $offset    = ($currpage-1)*$pagesize;//偏移量
        $list      = M($table)->field($filed)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
        return $list;
    }
    //分页+联合查询
    function currpages($table,$filed,$join,$where = null,$order,$pagesize,$currpage){
        $offset    = ($currpage-1)*$pagesize;//偏移量
        $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
        return $list;
    }



    //微信获取用户openid
    function codes($code){
        $openid = json_decode(wx($code), true);
        $openids = $openid['openid'];
        return $openids;
    }
    //含有用户expires_in，openid，session_key    wx3edf494269594a3b   cce78a86dce58d3287240a88b825189b
    function wx($code)
    {
        $appid     = APP;
        $appsecret = SECRET;
        $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
        $apiData = file_get_contents($apiUrl,true);//json_decode(file_get_contents($apiUrl,true),true);
        return $apiData;
    }
    function users($table,$field,$code){ //获取用户openid 获取用户信息
        $appid     = APP;
        $appsecret = SECRET;
        $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
        $apiData = file_get_contents($apiUrl,true);
        $openid  = json_decode($apiData, true);
        $openids = $openid['openid'];
        $user    = M($table)->field($field)->where(array("openid"=>$openids))->find();
        return $user;
    }
    //含有用户access_token，expires_in ，openid ，refresh_token， scope
    function wxs($code,$form_id)
    {
        $appid     = APP;
        $appsecret = SECRET;
        $apiUrl                   = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        $apiData                  = json_decode(file_get_contents($apiUrl,true),true);
        $apiData['template_id']  = "82Lyhv5KOOUte9dN16VnuyQ82cbRWLZjiUzuZsMeIhA";

        $muurl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$apiData['access_token']}&touser={$apiData['openid']}&template_id={$apiData['template_id']}&form_id={$form_id}&data=123";
        $mu    = json_decode(file_get_contents($muurl,true),true);
        return $mu;
    }
//腾讯地图数据处理
    function tx_map($from = null,$to = null,$clat = null,$clng = null){
        //$key      = "4CVBZ-PD5C6-Q2NS2-MRM6M-AUL22-7BF4L";                               //腾讯地图key值
        $key      = "2UVBZ-L5X3W-W3CRB-OK3RA-6WXQH-4VFOJ";
        //$from     = "西安市雁塔区高新路88号";
        //$to       = array("西安市雁塔区科技四路南窑头东区","西安市雁塔区科技一路","西安市雁塔区西辛庄");
        $to_count = count($to);
        //起点坐标
        if($clat != null && $clng != null){
            $lng     = $clng; // 经度
            $lat     = $clat;//维度
        }else{
            $url      = "http://apis.map.qq.com/ws/geocoder/v1/?address={$from}&key={$key}";
            $result  = json_decode(file_get_contents($url));
            $lng     = $result->result->location->lng; // 经度
            $lat     = $result->result->location->lat;//维度
        }

        //终点坐标
        $arr = "";
        for($i=0;$i<$to_count;$i++){
            $results = json_decode(file_get_contents("http://apis.map.qq.com/ws/geocoder/v1/?address={$to[$i]}&key={$key}"));
            $lngs     = $results->result->location->lng;
            $lats     = $results->result->location->lat;
            $arr     .= $lats.",".$lngs.";";
        }
        $arr = substr($arr,0,-1);
        //两点之间的距离
        $ju      = file_get_contents("http://apis.map.qq.com/ws/distance/v1/?mode=driving&from={$lat},{$lng}&to={$arr}&key={$key}");
        $ju = json_decode($ju);
        for($i=0;$i<$to_count;$i++){
            $mi[]      = $ju->result->elements[$i]->distance;
        }
        return $mi;
    }
    //腾讯地图数据处理
    function tx_maps($from = null,$to = null,$clat = null,$clng = null){
        $key      = "4CVBZ-PD5C6-Q2NS2-MRM6M-AUL22-7BF4L";                               //腾讯地图key值
        //$key      = "2UVBZ-L5X3W-W3CRB-OK3RA-6WXQH-4VFOJ";
        //起点坐标
        if($clat != null && $clng != null){
            $lng     = $clng; // 经度
            $lat     = $clat;//维度
        }else{
            $url      = "http://apis.map.qq.com/ws/geocoder/v1/?address={$from}&key={$key}";
            $result  = json_decode(file_get_contents($url));
            $lng     = $result->result->location->lng; // 经度
            $lat     = $result->result->location->lat;//维度
        }
        //终点坐标
        $results = json_decode(file_get_contents("http://apis.map.qq.com/ws/geocoder/v1/?address={$to}&key={$key}"));
        $lngs     = $results->result->location->lng;
        $lats     = $results->result->location->lat;

        //两点之间的距离
        $ju      = file_get_contents("http://apis.map.qq.com/ws/distance/v1/?mode=driving&from={$lat},{$lng}&to={$lats},{$lngs}&key={$key}");
        $ju = json_decode($ju);
        if($ju->message == "query ok"){
            $mi   = $ju->result->elements[0]->distance;
            $mi   = sprintf("%.1f",($mi/1000));  //精确三位小数
        }else{
            $mi = "10";
        }
        return $mi;
    }
    //生成二维码
    function code_s($data){
        require "Public/phpqrcode/qrlib.php";
        //$data = 'http://www.baidu.com';
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 6;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        //$path = "images/";
        // 生成的文件名
        //$fileName = $path.$size.'.png';
        QRcode::png($data, "Public/img/aa.png", $level, $size);


        //QRcode::png($data,"Public/img/aa.png");
    }
    //随机生成字符串
    function generate_password($length) {
        $chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
        $password = "";
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }
    //递归实现无限极分类
    function get_attr($a,$pid){
        $tree = array();                                //每次都声明一个新数组用来放子元素
        foreach($a as $v){
            if($v['pid'] == $pid){                      //匹配子记录
                $v['children'] = get_attr($a,$v['id']); //递归获取子记录
                if($v['children'] == null){
                    unset($v['children']);             //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
                }
                $tree[] = $v;                           //将记录存入新数组
            }
        }
        return $tree;                                  //返回新数组
    }
    //单图上传
    function imgUpload($path)
    {
        $config = array(
            'maxSize' => 3145728,
            'rootPath' => 'Data/',
            'savePath' => $path,
            'saveName' => time() . '_' . mt_rand(),
            'exts' => array('jpg', 'png', 'jpeg', 'gif'),
            'autoSub' => true,
            'subName' => array('date', 'Ymd')
        );
        $upload = new \Think\Upload($config);
        $info = $upload->upload();
        if (!$info) {
            $this->error($upload->getError());
        }
        return $info;
    }
